package com.songcan.basics.core.service;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.songcan.basics.properties.CodeProperties;
import com.songcan.common.contans.SmsTypeEnum;
import com.songcan.common.utils.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.songcan.common.contans.CoreContants.MOBILE_CODE;

@Component
@Slf4j
public class SmsService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CodeProperties codeProperties;

    public void sendMessage(SmsTypeEnum codeType, String mobile) {

        String template = null;
        switch (codeType) {
            case PAY_SUCCESS:

                break;
            case VERIFY_CODE:
                template = codeProperties.getUnkom();
                break;
            case BIND_MOBILE:
            case BIND_BANK_CARD:
                template = codeProperties.getBinding();
                break;
            case PAY_VERIFY:
                template = codeProperties.getPayment();
                break;
        }
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        redisTemplate.opsForValue().set(MOBILE_CODE+mobile,code,3, TimeUnit.MINUTES);
        String content = StrUtil.format(template, code);
        StringBuffer httpArgs = new StringBuffer();
        httpArgs.append("http://api.smsbao.com/sms?");
        httpArgs.append("u=").append(codeProperties.getUsername()).append("&");
        httpArgs.append("p=").append(MessageUtils.md5(codeProperties.getPassword())).append("&");
        httpArgs.append("m=").append(mobile).append("&");
        httpArgs.append("c=").append(MessageUtils.encodeUrlString(content, "UTF-8"));
        String result = HttpUtil.get(httpArgs.toString());
        log.info("发送验证码:{} , {}", code, result);
    }
}
